const express = require('express');
const cors = require('cors');
const app = express();
const userRouter = require("./router/user")
const joi = require('joi');
const userinfoRouter = require("./router/userinfo")
app.use(cors());
app.use(function(req,res,next){
    res.cc = function(err,status = 400){
        res.send({
            status,
            message:err instanceof Error ? err.message : err
        })
    }
    next();
})
const expressJWT = require("express-jwt");
const config = require("./config")
app.use(expressJWT({secret:config.jwtSecretKey}).unless({path:[/^\/api/]}))

//配置解析表单数据的中间件，只能解析application/x-www-form-urlencoded格式的表单数据
app.use(express.urlencoded({ extended: false }));
app.use("/api",userRouter);

app.use("/my",userinfoRouter);
const artcateRouter = require("./router/artcate")
app.use("/my/article",artcateRouter)
//错误中间件
app.use(function(err,req,res,next){
    if(err instanceof joi.ValidationError) {
        return res.send({
            status: 400,
            message: err.message
        });
    }
    if(err.name === "UnauthorizedError") {
        return res.send({
            status:401,
            message:"身份认证失败！"
        })
    }
    if(err.name ==="ERR_HTTP_HEADERS_SENT"){
        return res.send({
            status:500,
            message:"服务器错误！"
        })
    }
    res.cc(err);
})
app.listen(3000, () => {
    console.log('server at http://localhost:3000');
});
